<template>
  <div class="kafka-forward-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <div class="title-with-back">
          <el-button 
            type="primary" 
            :icon="ArrowLeft" 
            @click="$router.push('/tools')"
            class="blue-return-button"
            circle
          />
          <div class="title-content">
            <div class="title-main">
              <el-icon class="title-icon"><Connection /></el-icon>
              <h2>Kafka数据转发</h2>
            </div>
            <p class="page-description">
              <el-icon><Document /></el-icon>
              <span>从源Topic消费消息并转发到目标Topic，支持消息过滤、格式转换和批量处理</span>
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 当前任务状态 -->
    <div v-if="currentTaskStatus" class="current-task-status" style="margin-bottom: 20px;">
      <el-card>
        <template #header>
          <div class="card-header">
            <div class="card-header-title">
              <el-icon class="card-icon"><TrendCharts /></el-icon>
              <span>当前转发任务</span>
            </div>
            <el-tag :type="currentTaskStatus.status === 'running' ? 'success' : 'info'" size="small">
              {{ currentTaskStatus.status === 'running' ? '运行中' : '已停止' }}
            </el-tag>
          </div>
        </template>
        <div class="task-info">
          <div class="info-item">
            <label>任务ID:</label>
            <code>{{ currentTaskStatus.task_id }}</code>
          </div>
          <div class="info-item" v-if="currentTaskStatus.config">
            <label>源Topic:</label>
            <span>{{ currentTaskStatus.config.source_topic }}</span>
          </div>
          <div class="info-item" v-if="currentTaskStatus.config">
            <label>目标Topic:</label>
            <span>{{ currentTaskStatus.config.target_topic }}</span>
          </div>
          <div class="info-item" v-if="currentTaskStatus.config">
            <label>消费策略:</label>
            <el-tag size="small" :type="getConsumeStrategyTagType(currentTaskStatus.config.consume_strategy)">
              {{ getConsumeStrategyText(currentTaskStatus.config.consume_strategy) }}
            </el-tag>
          </div>
          <div class="info-item" v-if="currentTaskStatus.config && currentTaskStatus.config.consume_strategy === 'timestamp' && currentTaskStatus.config.start_timestamp">
            <label>开始时间:</label>
            <code>{{ formatTimestamp(currentTaskStatus.config.start_timestamp) }}</code>
          </div>
          <div class="info-item" v-if="currentTaskStatus.config">
            <label>转发策略:</label>
            <el-tag size="small" :type="getStrategyTagType(currentTaskStatus.config.forward_strategy)">
              {{ getStrategyText(currentTaskStatus.config.forward_strategy) }}
            </el-tag>
          </div>
        </div>
        <div class="task-actions" style="margin-top: 16px;">
          <el-button 
            type="danger" 
            size="small" 
            @click="stopCurrentTask"
            :loading="stopTaskLoading"
            v-if="currentTaskStatus.status === 'running'"
          >
            停止任务
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="refreshTaskStatus"
            :loading="statusLoading"
          >
            刷新状态
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 转发配置表单 - 只在没有运行任务时显示 -->
    <el-card v-if="!currentTaskStatus || currentTaskStatus.status !== 'running'" class="config-card">
      <template #header>
        <div class="card-header">
          <div class="card-header-title">
            <el-icon class="card-icon"><Setting /></el-icon>
            <span>转发配置</span>
          </div>
          <el-button @click="loadKafkaEnvironments" :icon="Refresh" size="small">刷新环境</el-button>
        </div>
      </template>
      
      <el-form 
        :model="forwardConfig" 
        label-width="140px" 
        :rules="configRules"
        ref="configFormRef"
      >
        <!-- Kafka环境选择 -->
        <el-form-item label="Kafka环境:" prop="kafkaConfigId">
          <el-select 
            v-model="forwardConfig.kafkaConfigId" 
            placeholder="选择Kafka环境"
            style="width: 300px"
            @change="onKafkaConfigChange"
            @focus="onEnvironmentSelectFocus"
            :loading="environmentsLoading"
          >
            <el-option
              v-for="config in kafkaEnvironments"
              :key="config.id"
              :label="`${config.config_name || config.name} (${config.host || config.bootstrap_servers}:${config.port || ''})`"
              :value="config.id"
            >
              <div style="display: flex; justify-content: space-between;">
                <span>{{ config.config_name || config.name }}</span>
                <span style="color: #8492a6; font-size: 12px">{{ config.host || config.bootstrap_servers }}:{{ config.port || '' }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 源Topic -->
        <el-form-item label="源Topic:" prop="sourceTopic">
          <div style="display: flex; gap: 8px; align-items: center;">
            <el-autocomplete
              v-model="forwardConfig.sourceTopic"
              :fetch-suggestions="queryTopicSuggestions"
              placeholder="输入或选择源Topic"
              style="width: 250px"
              :debounce="300"
              clearable
            >
              <template #default="{ item }">
                <div class="topic-suggestion-item">
                  <el-icon><Menu /></el-icon>
                  <span>{{ item.value }}</span>
                </div>
              </template>
            </el-autocomplete>
            <el-button @click="openTopicSelector('source')" :icon="Menu" title="从列表选择" size="small"></el-button>
          </div>
        </el-form-item>

        <!-- 消费策略 -->
        <el-form-item label="消费策略:">
          <el-select v-model="forwardConfig.consumeStrategy" style="width: 120px">
            <el-option label="最新" value="latest" />
            <el-option label="最早" value="earliest" />
            <el-option label="指定时间" value="timestamp" />
          </el-select>
        </el-form-item>

        <!-- 时间戳选择 -->
        <el-form-item v-if="forwardConfig.consumeStrategy === 'timestamp'" label="开始时间:">
          <el-input 
            v-model="timestampDisplay"
            placeholder="选择开始时间"
            readonly
            style="width: 320px; cursor: pointer;"
            @click="openTimestampSelector"
          >
            <template #suffix>
              <el-icon class="timestamp-icon">
                <Calendar />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 目标Topic -->
        <el-form-item label="目标Topic:" prop="targetTopic">
          <div style="display: flex; gap: 8px; align-items: center;">
            <el-autocomplete
              v-model="forwardConfig.targetTopic"
              :fetch-suggestions="queryTopicSuggestions"
              placeholder="输入或选择目标Topic"
              style="width: 250px"
              :debounce="300"
              clearable
            >
              <template #default="{ item }">
                <div class="topic-suggestion-item">
                  <el-icon><Menu /></el-icon>
                  <span>{{ item.value }}</span>
                </div>
              </template>
            </el-autocomplete>
            <el-button @click="openTopicSelector('target')" :icon="Menu" title="从列表选择" size="small"></el-button>
          </div>
        </el-form-item>

        <!-- 转发策略 -->
        <el-form-item label="转发策略:" prop="forwardStrategy">
          <el-radio-group v-model="forwardConfig.forwardStrategy">
            <el-radio value="all">全部转发</el-radio>
            <el-radio value="filter">条件过滤</el-radio>
            <el-radio value="replace">字段替换</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 条件过滤配置 -->
        <el-form-item v-if="forwardConfig.forwardStrategy === 'filter'" label="过滤配置:" class="filter-config-item">
          <div class="match-config-container">
            <!-- 逻辑关系选择 -->
            <div class="logic-selector">
              <label class="control-label">多条件逻辑关系：</label>
              <el-radio-group v-model="forwardConfig.logicOperator" class="logic-operator">
                <el-radio value="AND">
                  <el-tag type="success">AND (与)</el-tag>
                  <span style="margin-left: 8px; color: #666;">所有条件都必须满足</span>
                </el-radio>
                <el-radio value="OR">
                  <el-tag type="warning">OR (或)</el-tag>
                  <span style="margin-left: 8px; color: #666;">任意条件满足即可</span>
                </el-radio>
              </el-radio-group>
            </div>

            <!-- 匹配条件列表 -->
            <div class="conditions-list">
              <div v-for="(condition, index) in forwardConfig.matchConditions" :key="index" class="condition-item">
                <el-card shadow="never" class="condition-card">
                  <div class="condition-header">
                    <span class="condition-number">条件 {{ index + 1 }}</span>
                    <el-button 
                      @click="removeMatchCondition(index)" 
                      type="danger" 
                      size="small" 
                      :icon="Delete"
                      circle
                      :disabled="forwardConfig.matchConditions.length === 1"
                    />
                  </div>
                  
                  <div class="condition-content">
                    <!-- 匹配类型 -->
                    <div class="condition-row">
                      <label class="condition-label">匹配类型：</label>
                      <el-radio-group v-model="condition.type" class="condition-type">
                        <el-radio value="key_value">键值对匹配</el-radio>
                        <el-radio value="fuzzy">模糊匹配</el-radio>
                      </el-radio-group>
                    </div>

                    <!-- 键值对匹配输入 -->
                    <div v-if="condition.type === 'key_value'" class="condition-row">
                      <div class="input-group">
                        <label class="input-label">键名 (Key) - 完整路径</label>
                        <el-input
                          v-model="condition.key"
                          placeholder="例如: data.itemId"
                          style="width: 200px"
                        />
                      </div>
                      <div class="input-group">
                        <label class="input-label">期望值 (Value)</label>
                        <el-input
                          v-model="condition.value"
                          placeholder="例如: 12345"
                          style="width: 200px"
                        />
                      </div>
                    </div>

                    <!-- 模糊匹配输入 -->
                    <div v-if="condition.type === 'fuzzy'" class="condition-row">
                      <div class="input-group">
                        <label class="input-label">搜索内容</label>
                        <el-input
                          v-model="condition.value"
                          placeholder="例如: 关键字、短语等"
                          style="width: 300px"
                        />
                      </div>
                    </div>
                  </div>
                </el-card>
              </div>
              
              <el-button 
                type="primary" 
                size="small" 
                :icon="Plus" 
                @click="addMatchCondition"
                class="add-condition-btn"
              >
                添加条件
              </el-button>
            </div>
          </div>
        </el-form-item>

        <!-- 字段替换配置 -->
        <el-form-item v-if="forwardConfig.forwardStrategy === 'replace'" label="替换配置:" class="filter-config-item">
          <div class="match-config-container">
            <div class="replace-info">
              <div class="replace-info-card">
                <div class="info-header" @click="toggleReplaceHelp" style="cursor: pointer;">
                  <el-icon class="info-icon"><InfoFilled /></el-icon>
                  <span class="info-title">字段替换说明</span>
                  <el-icon class="toggle-icon" :class="{ 'is-expanded': showReplaceHelp }">
                    <ArrowDown />
                  </el-icon>
                </div>
                
                <el-collapse-transition>
                  <div v-show="showReplaceHelp" class="info-content">
                    <div class="info-section">
                      <div class="section-title">
                        <el-icon><Setting /></el-icon>
                        <span>功能说明</span>
                      </div>
                      <div class="info-grid">
                        <div class="info-item">
                          <el-icon class="item-icon" color="#67c23a"><Select /></el-icon>
                          <div class="item-content">
                            <div class="item-label">嵌套路径</div>
                            <div class="item-text">用点号<code>(.)</code>分隔，如 <code>context.task_id</code></div>
                          </div>
                        </div>
                        <div class="info-item">
                          <el-icon class="item-icon" color="#409eff"><Edit /></el-icon>
                          <div class="item-content">
                            <div class="item-label">智能处理</div>
                            <div class="item-text">字段不存在则创建，存在则覆盖原值</div>
                          </div>
                        </div>
                        <div class="info-item">
                          <el-icon class="item-icon" color="#e6a23c"><Connection /></el-icon>
                          <div class="item-content">
                            <div class="item-label">批量操作</div>
                            <div class="item-text">支持同时替换多个字段的值</div>
                          </div>
                        </div>
                        <div class="info-item">
                          <el-icon class="item-icon" color="#9c27b0"><DataAnalysis /></el-icon>
                          <div class="item-content">
                            <div class="item-label">数据类型</div>
                            <div class="item-text">字符串、数字、布尔值、null</div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div class="info-section">
                      <div class="section-title">
                        <el-icon><Document /></el-icon>
                        <span>使用示例</span>
                      </div>
                      <div class="example-list">
                        <div class="example-item">
                          <code class="field-path">context.task_id</code>
                          <el-icon class="example-arrow"><Right /></el-icon>
                          <code class="field-value string-value">"test123"</code>
                          <el-tag size="small" type="success">字符串</el-tag>
                        </div>
                        <div class="example-item">
                          <code class="field-path">context.task_type</code>
                          <el-icon class="example-arrow"><Right /></el-icon>
                          <code class="field-value number-value">2</code>
                          <el-tag size="small" type="warning">数字</el-tag>
                        </div>
                        <div class="example-item">
                          <code class="field-path">data.user.nickname</code>
                          <el-icon class="example-arrow"><Right /></el-icon>
                          <code class="field-value string-value">"新用户名"</code>
                          <el-tag size="small" type="success">字符串</el-tag>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-collapse-transition>
              </div>
            </div>

            <!-- 替换规则列表 -->
            <div class="conditions-list" style="margin-top: 16px;">
              <div v-for="(rule, index) in forwardConfig.replaceRules" :key="index" class="condition-item">
                <el-card shadow="never" class="condition-card">
                  <div class="condition-header">
                    <span class="condition-number">替换规则 {{ index + 1 }}</span>
                    <el-button 
                      @click="removeReplaceRule(index)" 
                      type="danger" 
                      size="small" 
                      :icon="Delete"
                      circle
                      :disabled="forwardConfig.replaceRules.length === 1"
                    />
                  </div>
                  
                  <div class="condition-content">
                    <div class="condition-row">
                      <div class="input-group" style="flex: 1 1 100%;">
                        <label class="input-label">字段路径 (支持嵌套)</label>
                        <el-input
                          v-model="rule.fieldPath"
                          placeholder="例如: context.task_id"
                          @blur="rule.fieldPath = rule.fieldPath.trim()"
                        >
                          <template #prepend>
                            <el-icon><Key /></el-icon>
                          </template>
                        </el-input>
                        <span class="field-hint">用点号(.)分隔嵌套字段</span>
                      </div>
                    </div>
                    
                    <div class="condition-row">
                      <div class="input-group" style="flex: 2;">
                        <label class="input-label">新值</label>
                        <el-input
                          v-model="rule.newValue"
                          placeholder="例如: test1"
                        >
                          <template #prepend>
                            <el-icon><Edit /></el-icon>
                          </template>
                        </el-input>
                      </div>
                      
                      <div class="input-group" style="flex: 1; min-width: 120px;">
                        <label class="input-label">值类型</label>
                        <el-select v-model="rule.valueType" style="width: 100%">
                          <el-option label="字符串" value="string" />
                          <el-option label="数字" value="number" />
                          <el-option label="布尔值" value="boolean" />
                          <el-option label="null" value="null" />
                        </el-select>
                      </div>
                    </div>

                    <!-- 实时预览 -->
                    <div class="replace-preview" v-if="rule.fieldPath && rule.newValue">
                      <div class="preview-label">
                        <el-icon><View /></el-icon>
                        <span>替换预览:</span>
                      </div>
                      <div class="preview-content">
                        <code>{{ rule.fieldPath }}</code>
                        <el-icon class="preview-arrow"><Right /></el-icon>
                        <code class="new-value">{{ formatPreviewValue(rule.newValue, rule.valueType) }}</code>
                        <el-tag size="small" type="info">{{ getValueTypeLabel(rule.valueType) }}</el-tag>
                      </div>
                    </div>
                  </div>
                </el-card>
              </div>
              
              <el-button 
                type="primary" 
                size="small" 
                :icon="Plus" 
                @click="addReplaceRule"
                class="add-condition-btn"
              >
                添加替换规则
              </el-button>
            </div>
          </div>
        </el-form-item>

        <!-- 批量大小 -->
        <el-form-item label="批量大小:" prop="batchSize">
          <div style="display: flex; align-items: center; gap: 15px;">
            <!-- 智能/自定义切换开关 -->
            <div style="display: flex; align-items: center; gap: 8px; padding: 4px; background: #f5f7fa; border-radius: 20px;">
              <el-button 
                :type="forwardConfig.batchSize === 0 ? 'primary' : ''"
                size="small"
                round
                @click="forwardConfig.batchSize = 0"
                style="min-width: 80px;"
              >
                <span v-if="forwardConfig.batchSize === 0">✓ </span>智能
              </el-button>
              <el-button 
                :type="forwardConfig.batchSize > 0 ? 'primary' : ''"
                size="small"
                round
                @click="forwardConfig.batchSize = 100"
                style="min-width: 80px;"
              >
                <span v-if="forwardConfig.batchSize > 0">✓ </span>自定义
              </el-button>
            </div>
            
            <!-- 自定义输入框（只在自定义模式显示） -->
            <el-input-number 
              v-if="forwardConfig.batchSize > 0"
              v-model="forwardConfig.batchSize" 
              :min="1" 
              :max="10000" 
              placeholder="输入批量大小"
              style="width: 180px"
            />
            
            <!-- 状态提示 -->
            <span style="color: #909399; font-size: 12px;">
              <span v-if="forwardConfig.batchSize === 0" style="color: #67c23a;">
                🚀 自动根据消费策略优化
              </span>
              <span v-else style="color: #409eff;">
                每次拉取 {{ forwardConfig.batchSize }} 条消息
              </span>
            </span>
          </div>
        </el-form-item>

        <!-- 处理间隔 -->
        <el-form-item label="处理间隔:" prop="processInterval">
          <el-input-number 
            v-model="forwardConfig.processInterval" 
            :min="100" 
            :max="60000" 
            placeholder="处理间隔(毫秒)"
            style="width: 200px"
          />
          <span style="margin-left: 10px; color: #909399; font-size: 12px;">
            毫秒，建议1000-5000
          </span>
        </el-form-item>

        <!-- 转发条数限制 -->
        <el-form-item label="转发条数:" prop="maxForwardCount">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-radio-group v-model="forwardConfig.countLimitType" @change="onCountLimitTypeChange">
              <el-radio value="unlimited">全部转发</el-radio>
              <el-radio value="limited">限制条数</el-radio>
            </el-radio-group>
            <el-input-number 
              v-model="forwardConfig.maxForwardCount" 
              :min="1" 
              :max="1000000" 
              placeholder="最大转发条数"
              style="width: 180px"
              :disabled="forwardConfig.countLimitType === 'unlimited'"
            />
            <span style="color: #909399; font-size: 12px;">
              {{ forwardConfig.countLimitType === 'unlimited' ? '无限制，转发所有匹配消息' : '先到先转发，达到数量后自动停止' }}
            </span>
          </div>
        </el-form-item>

        <!-- 启动按钮 -->
        <el-form-item>
          <el-button 
            type="primary" 
            @click="startForwarding"
            :loading="startLoading"
            size="large"
          >
            <el-icon><VideoPlay /></el-icon>
            启动转发任务
          </el-button>
          <el-button 
            @click="resetForm"
            size="large"
          >
            <el-icon><RefreshRight /></el-icon>
            重置配置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 无任务时的提示信息 -->
    <div v-if="!currentTaskStatus" class="no-task-hint" style="margin-top: 20px;">
      <el-empty description="暂无转发任务运行" />
    </div>

    <!-- 转发统计 -->
    <div v-if="forwardStats && Object.keys(forwardStats).length > 0" class="stats-panel" style="margin-top: 20px;">
      <el-card>
        <template #header>
          <div class="card-header">
            <div class="card-header-title">
              <el-icon class="card-icon"><DataAnalysis /></el-icon>
              <span>转发统计</span>
            </div>
            <el-tag size="small" type="success">实时</el-tag>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="已处理消息" :value="forwardStats.processed_count || 0" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="转发成功" :value="forwardStats.forwarded_count || 0" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="过滤消息" :value="forwardStats.filtered_count || 0" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="错误数量" :value="forwardStats.error_count || 0" />
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- Topic选择器弹窗 -->
    <el-dialog v-model="showTopicSelector" title="输入或选择topic" width="700px">
      <div style="margin-bottom: 16px;">
        <div style="display: flex; gap: 12px; align-items: center;">
          <el-input
            v-model="topicSearchKeyword"
            placeholder="搜索Topic名称..."
            :prefix-icon="Search"
            clearable
            style="flex: 1;"
            @input="handleTopicSearch"
          />
          <el-button @click="loadTopics" :loading="topicsLoading" :icon="Refresh">刷新</el-button>
        </div>
        
        <!-- 搜索统计信息 -->
        <div v-if="topicSearchKeyword" style="margin-top: 8px; font-size: 12px; color: #909399;">
          找到 {{ filteredTopics.length }} 个匹配的Topic（共 {{ topics.length }} 个）
        </div>
      </div>
      
      <el-table 
        :data="filteredTopics" 
        height="350px"
        @row-click="selectTopic"
        style="cursor: pointer;"
        :empty-text="topicSearchKeyword ? '未找到匹配的Topic' : '暂无Topic数据'"
      >
        <el-table-column prop="name" label="Topic名称">
          <template #default="{ row }">
            <div v-if="topicSearchKeyword">
              <span v-html="highlightSearchKeyword(row.name)"></span>
            </div>
            <div v-else>
              {{ row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click.stop="selectTopic(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <template #footer>
        <el-button @click="showTopicSelector = false">取消</el-button>
      </template>
    </el-dialog>

    <!-- 时间戳选择器弹窗 -->
    <el-dialog v-model="showTimestampDialog" title="选择时间戳" width="600px">
      <div class="timestamp-dialog">
        <div class="timestamp-info">
          <el-alert 
            title="时间戳说明" 
            type="info" 
            :closable="false"
            show-icon
          >
            <p>选择消费开始时间，系统将从指定时间点开始消费Kafka消息</p>
            <p>• 日期时间将自动转换为毫秒时间戳</p>
            <p>• 如果指定时间没有消息，将从下一条可用消息开始</p>
          </el-alert>
        </div>
        
        <div class="timestamp-selector">
          <div class="datetime-inputs">
            <div class="input-group">
              <label>选择日期:</label>
              <el-date-picker
                v-model="tempDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 200px"
              />
            </div>
            
            <div class="input-group">
              <label>选择时间:</label>
              <el-time-picker
                v-model="tempTime"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                placeholder="选择时间"
                style="width: 200px"
              />
            </div>
          </div>
          
          <div class="timestamp-preview">
            <div class="preview-info">
              <label>时间戳预览:</label>
              <div class="preview-values">
                <div class="preview-item">
                  <span class="label">日期时间:</span>
                  <code>{{ tempDate && tempTime ? `${tempDate} ${tempTime}` : '请选择日期和时间' }}</code>
                </div>
                <div class="preview-item">
                  <span class="label">毫秒时间戳:</span>
                  <code>{{ tempDate && tempTime ? getTimestampPreview() : '0' }}</code>
                </div>
              </div>
            </div>
          </div>
          
          <div class="quick-select-section">
            <div class="quick-select-info">
              <label>快捷选择:</label>
              <p class="usage-tip">该时间戳将用作Kafka消费的起始位置，消费该时间点之后的消息</p>
            </div>
            <div class="quick-select-buttons">
              <el-button size="small" @click="setQuickTime('1h')">1小时前</el-button>
              <el-button size="small" @click="setQuickTime('6h')">6小时前</el-button>
              <el-button size="small" @click="setQuickTime('12h')">12小时前</el-button>
              <el-button size="small" @click="setQuickTime('today')">今天开始</el-button>
              <el-button size="small" @click="setQuickTime('yesterday')">昨天开始</el-button>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showTimestampDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmTimestamp">插入时间戳</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, Connection, Setting, VideoPlay, RefreshRight, 
  Plus, Delete, DataAnalysis, Refresh, Menu, Search, Calendar,
  Document, TrendCharts, Key, Edit, View, Right, InfoFilled, Select,
  ArrowDown
} from '@element-plus/icons-vue'
import { componentLogger } from '@/utils/logger'
import api from '@/utils/api'

const router = useRouter()

// 响应式数据
const kafkaEnvironments = ref([])
const topics = ref([])
const filteredTopics = ref([])
const currentTaskStatus = ref(null)
const forwardStats = ref({})
const startLoading = ref(false)
const stopTaskLoading = ref(false)
const statusLoading = ref(false)
const topicsLoading = ref(false)
const configFormRef = ref(null)

// Topic选择器相关
const showTopicSelector = ref(false)
const topicSearchKeyword = ref('')
const topicSelectorType = ref('source') // 'source' 或 'target'

// 时间戳选择器相关
const showTimestampDialog = ref(false)
const tempDate = ref('')
const tempTime = ref('')
const timestampDisplay = ref('')

// 字段替换说明展开/收起
const showReplaceHelp = ref(false)

// 定时器
const statusTimer = ref(null)
const statsTimer = ref(null)
// 无任务轮询计数器
const noTaskPollCount = ref(0)
const MAX_NO_TASK_POLLS = 3 // 连续3次没有任务就停止轮询

// 转发配置
const forwardConfig = ref({
  kafkaConfigId: null,
  sourceTopic: '',
  targetTopic: '',
  consumeStrategy: 'latest',
  startTime: null,
  forwardStrategy: 'all',
  logicOperator: 'AND',
  matchConditions: [
    {
      type: 'key_value',
      key: '',
      value: ''
    }
  ],
  replaceRules: [
    {
      fieldPath: '',
      newValue: '',
      valueType: 'string'
    }
  ],
  batchSize: 100,
  processInterval: 1000,
  countLimitType: 'unlimited', // 'unlimited' | 'limited'
  maxForwardCount: 1000
})

// 表单验证规则
const configRules = {
  kafkaConfigId: [
    { required: true, message: '请选择Kafka环境', trigger: 'change' }
  ],
  sourceTopic: [
    { required: true, message: '请输入源Topic', trigger: 'blur' }
  ],
  targetTopic: [
    { required: true, message: '请输入目标Topic', trigger: 'blur' }
  ],
  forwardStrategy: [
    { required: true, message: '请选择转发策略', trigger: 'change' }
  ],
  batchSize: [
    { required: true, message: '请输入批量大小', trigger: 'blur' },
    { type: 'number', min: 0, max: 10000, message: '批量大小必须在0-10000之间 (0=智能调整)', trigger: 'blur' }
  ],
  processInterval: [
    { required: true, message: '请输入处理间隔', trigger: 'blur' },
    { type: 'number', min: 100, max: 60000, message: '处理间隔必须在100-60000毫秒之间', trigger: 'blur' }
  ]
}

// 组件挂载时初始化
onMounted(async () => {
  componentLogger.info('Kafka转发页面已加载')
  noTaskPollCount.value = 0 // 重置计数器
  // 不自动加载环境列表，等待用户手动选择
  // 检查是否有正在运行的任务
  await checkCurrentTaskStatus()
  startStatusPolling()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopStatusPolling()
  stopStatsPolling()
})

// 时间戳选择器相关方法
const initTimestampDialog = () => {
  const now = new Date()
  tempDate.value = now.toISOString().split('T')[0]
  tempTime.value = now.toTimeString().split(' ')[0]
}

const getTimestampPreview = () => {
  if (!tempDate.value || !tempTime.value) return 0
  const dateTime = new Date(`${tempDate.value}T${tempTime.value}`)
  return dateTime.getTime()
}

const confirmTimestamp = () => {
  if (!tempDate.value || !tempTime.value) {
    ElMessage.warning('请选择日期和时间')
    return
  }
  
  const timestamp = getTimestampPreview()
  const dateTimeStr = `${tempDate.value} ${tempTime.value}`
  
  forwardConfig.value.startTime = timestamp
  timestampDisplay.value = `${dateTimeStr}`
  
  showTimestampDialog.value = false
  ElMessage.success('时间戳设置成功')
}

const openTimestampSelector = () => {
  if (!forwardConfig.value.startTime) {
    initTimestampDialog()
  } else {
    const date = new Date(forwardConfig.value.startTime)
    tempDate.value = date.toISOString().split('T')[0]
    tempTime.value = date.toTimeString().split(' ')[0]
  }
  showTimestampDialog.value = true
}

// 快捷时间选择
const setQuickTime = (type) => {
  const now = new Date()
  let targetTime
  
  switch (type) {
    case '1h':
      targetTime = new Date(now.getTime() - 1 * 60 * 60 * 1000)
      break
    case '6h':
      targetTime = new Date(now.getTime() - 6 * 60 * 60 * 1000)
      break
    case '12h':
      targetTime = new Date(now.getTime() - 12 * 60 * 60 * 1000)
      break
    case 'today':
      targetTime = new Date(now)
      targetTime.setHours(0, 0, 0, 0)
      break
    case 'yesterday':
      targetTime = new Date(now)
      targetTime.setDate(now.getDate() - 1)
      targetTime.setHours(0, 0, 0, 0)
      break
    default:
      targetTime = now
  }
  
  // 设置临时日期和时间
  tempDate.value = targetTime.toISOString().split('T')[0]
  tempTime.value = targetTime.toTimeString().split(' ')[0]
  
  ElMessage.success(`已设置为${getQuickTimeLabel(type)}`)
}

// 获取快捷时间标签
const getQuickTimeLabel = (type) => {
  const labelMap = {
    '1h': '1小时前',
    '6h': '6小时前',
    '12h': '12小时前',
    'today': '今天开始',
    'yesterday': '昨天开始'
  }
  return labelMap[type] || '未知'
}

// 转发条数限制类型变化处理
const onCountLimitTypeChange = (type) => {
  if (type === 'unlimited') {
    forwardConfig.value.maxForwardCount = 0
  } else if (type === 'limited' && forwardConfig.value.maxForwardCount === 0) {
    forwardConfig.value.maxForwardCount = 1000
  }
}

// 加载Kafka环境列表
const environmentsLoading = ref(false)

// 环境选择器聚焦时加载环境列表（只加载一次）
const onEnvironmentSelectFocus = () => {
  if (kafkaEnvironments.value.length === 0 && !environmentsLoading.value) {
    loadKafkaEnvironments()
  }
}

const loadKafkaEnvironments = async () => {
  // 防止重复加载
  if (environmentsLoading.value) {
    componentLogger.warn('环境加载中,请稍候')
    return
  }
  
  environmentsLoading.value = true
  try {
    const response = await api.get('/kafka-listener/environments', {
      timeout: 10000 // 10秒超时
    })
    if (response.data.success) {
      kafkaEnvironments.value = response.data.data || []
      if (kafkaEnvironments.value.length === 0) {
        ElMessage.warning('未找到可用的Kafka环境配置')
      } else {
        componentLogger.info('Kafka环境加载成功', kafkaEnvironments.value.length)
      }
    } else {
      ElMessage.error('加载Kafka环境失败: ' + response.data.message)
      kafkaEnvironments.value = []
    }
  } catch (error) {
    componentLogger.error('加载Kafka环境异常', error)
    kafkaEnvironments.value = [] // 确保清空
    ElMessage.error({
      message: '加载Kafka环境失败: ' + (error.message || '网络错误'),
      duration: 5000
    })
  } finally {
    environmentsLoading.value = false
  }
}

// 检查当前任务状态
const checkCurrentTaskStatus = async () => {
  try {
    statusLoading.value = true
    const response = await api.get('/kafka-forward/status', {
      timeout: 8000 // 8秒超时
    })
    if (response.data.success) {
      const newTaskData = response.data.data
      
      // 检查任务ID是否发生变化
      if (currentTaskStatus.value && newTaskData && 
          currentTaskStatus.value.task_id !== newTaskData.task_id) {
        componentLogger.info(`检测到任务切换: ${currentTaskStatus.value.task_id} → ${newTaskData.task_id}`)
        ElMessage.warning('检测到任务已被新任务替换，正在停止新任务并重置页面')
        
        try {
          // 停止新任务
          const stopResponse = await api.post('/kafka-forward/stop')
          if (stopResponse.data.success) {
            componentLogger.info('新任务已成功停止')
            ElMessage.success('新任务已停止，页面已重置')
          } else {
            componentLogger.warn('停止新任务失败:', stopResponse.data.message)
          }
        } catch (error) {
          componentLogger.error('停止新任务异常:', error)
        }
        
        // 任务被替换时，清空状态并回到默认页面
        currentTaskStatus.value = null
        stopStatsPolling()
        stopStatusPolling()
        
        // 重置表单到初始状态
        resetForm()
        
        return // 不继续处理新任务数据
      }
      
      currentTaskStatus.value = newTaskData
      
      // 如果任务正在运行，开始统计轮询
      if (currentTaskStatus.value?.status === 'running') {
        startStatsPolling()
      } else {
        stopStatsPolling()
      }
    } else {
      // 如果之前有任务现在没有了，说明任务被停止
      if (currentTaskStatus.value) {
        componentLogger.info('任务已停止或被终止')
        ElMessage.warning('转发任务已停止')
      }
      currentTaskStatus.value = null
    }
  } catch (error) {
    componentLogger.error('检查任务状态异常', error)
    // 网络错误时不清空当前状态,避免频繁闪烁
    if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
      componentLogger.warn('状态检查超时,将在下次重试')
    } else {
      // 其他错误才清空状态
      currentTaskStatus.value = null
    }
  } finally {
    statusLoading.value = false
  }
}

// 启动状态轮询 - 智能轮询频率
const startStatusPolling = () => {
  if (statusTimer.value) return
  
  const pollStatus = async () => {
    await checkCurrentTaskStatus()
    
    // 根据任务状态调整轮询频率和停止条件
    const hasRunningTask = currentTaskStatus.value?.status === 'running'
    
    if (hasRunningTask) {
      // 有任务时重置计数器，高频轮询
      noTaskPollCount.value = 0
      statusTimer.value = setTimeout(pollStatus, 3000)
    } else {
      // 无任务时增加计数器
      noTaskPollCount.value++
      
      if (noTaskPollCount.value >= MAX_NO_TASK_POLLS) {
        // 连续多次无任务，停止轮询
        componentLogger.info(`连续${MAX_NO_TASK_POLLS}次轮询无任务，停止状态轮询`)
        statusTimer.value = null
        return
      } else {
        // 继续轮询，但频率较低
        statusTimer.value = setTimeout(pollStatus, 10000)
      }
    }
  }
  
  pollStatus()
}

// 停止状态轮询
const stopStatusPolling = () => {
  if (statusTimer.value) {
    clearTimeout(statusTimer.value)
    statusTimer.value = null
  }
}

// 启动统计轮询
const startStatsPolling = () => {
  if (statsTimer.value) return
  statsTimer.value = setInterval(loadForwardStats, 2000)
}

// 停止统计轮询
const stopStatsPolling = () => {
  if (statsTimer.value) {
    clearInterval(statsTimer.value)
    statsTimer.value = null
  }
}

// 加载转发统计
const loadForwardStats = async () => {
  try {
    const response = await api.get('/kafka-forward/stats', {
      timeout: 5000 // 5秒超时
    })
    if (response.data.success) {
      forwardStats.value = response.data.data
    }
  } catch (error) {
    // 静默处理错误,不影响用户体验
    if (error.code !== 'ECONNABORTED' && !error.message.includes('timeout')) {
      componentLogger.error('加载转发统计异常', error)
    }
  }
}

// Kafka配置变更处理
const onKafkaConfigChange = (configId) => {
  componentLogger.info('Kafka配置已变更', configId)
  // 清空Topic选择
  forwardConfig.value.sourceTopic = ''
  forwardConfig.value.targetTopic = ''
  // 加载新环境的Topic列表
  loadTopics()
}

// 加载Topic列表
const loadTopics = async () => {
  if (!forwardConfig.value.kafkaConfigId) return
  
  topicsLoading.value = true
  try {
    const response = await api.get('/kafka-listener/topics', {
      params: { kafka_config_id: forwardConfig.value.kafkaConfigId },
      timeout: 10000 // 10秒超时
    })
    if (response.data.success) {
      // 将字符串数组转换为对象数组以支持表格显示
      topics.value = response.data.data.map(topicName => ({ name: topicName }))
      // 初始化过滤列表
      filteredTopics.value = [...topics.value]
      componentLogger.info('Topic列表加载成功', { count: topics.value.length })
    } else {
      throw new Error(response.data.message || '获取Topic失败')
    }
  } catch (error) {
    componentLogger.error('加载Topic列表失败', error)
    ElMessage.error('加载Topic列表失败')
    topics.value = []
    filteredTopics.value = []
  } finally {
    topicsLoading.value = false
  }
}

// Topic自动完成搜索
const queryTopicSuggestions = (queryString, callback) => {
  // 如果没有加载Topic列表，先加载
  if (topics.value.length === 0) {
    loadTopics().then(() => {
      performTopicSearch(queryString, callback)
    })
  } else {
    performTopicSearch(queryString, callback)
  }
}

// 执行Topic搜索
const performTopicSearch = (queryString, callback) => {
  if (!queryString || queryString.trim() === '') {
    // 如果没有输入，显示前10个Topic作为提示
    const suggestions = topics.value.slice(0, 10).map(topic => ({
      value: topic.name
    }))
    callback(suggestions)
    return
  }
  
  // 模糊搜索匹配
  const keyword = queryString.toLowerCase()
  const matchedTopics = topics.value.filter(topic => 
    topic.name.toLowerCase().includes(keyword)
  ).slice(0, 20) // 限制显示20个结果
  
  const suggestions = matchedTopics.map(topic => ({
    value: topic.name
  }))
  
  callback(suggestions)
}

// 打开Topic选择器
const openTopicSelector = (type) => {
  topicSelectorType.value = type
  // 重置搜索状态
  topicSearchKeyword.value = ''
  filteredTopics.value = [...topics.value]
  showTopicSelector.value = true
  
  // 如果没有Topic数据，自动加载
  if (topics.value.length === 0) {
    loadTopics()
  }
}

// 输入或选择topic
const selectTopic = (topicRow) => {
  if (topicSelectorType.value === 'source') {
    forwardConfig.value.sourceTopic = topicRow.name
    ElMessage.success(`已选择源Topic: ${topicRow.name}`)
  } else {
    forwardConfig.value.targetTopic = topicRow.name
    ElMessage.success(`已选择目标Topic: ${topicRow.name}`)
  }
  showTopicSelector.value = false
}

// 处理Topic搜索
const handleTopicSearch = (keyword) => {
  if (!keyword || keyword.trim() === '') {
    filteredTopics.value = [...topics.value]
    return
  }
  
  const searchKeyword = keyword.toLowerCase()
  filteredTopics.value = topics.value.filter(topic =>
    topic.name.toLowerCase().includes(searchKeyword)
  )
}

// 高亮搜索关键词
const highlightSearchKeyword = (text) => {
  if (!topicSearchKeyword.value) return text
  
  const keyword = topicSearchKeyword.value.toLowerCase()
  const regex = new RegExp(`(${keyword})`, 'gi')
  return text.replace(regex, '<mark style="background-color: yellow; padding: 0;">$1</mark>')
}

// 添加匹配条件
const addMatchCondition = () => {
  forwardConfig.value.matchConditions.push({
    type: 'key_value',
    key: '',
    value: ''
  })
}

// 移除匹配条件
const removeMatchCondition = (index) => {
  if (forwardConfig.value.matchConditions.length > 1) {
    forwardConfig.value.matchConditions.splice(index, 1)
  }
}

// 添加替换规则
const addReplaceRule = () => {
  forwardConfig.value.replaceRules.push({
    fieldPath: '',
    newValue: '',
    valueType: 'string'
  })
}

// 移除替换规则
const removeReplaceRule = (index) => {
  if (forwardConfig.value.replaceRules.length > 1) {
    forwardConfig.value.replaceRules.splice(index, 1)
  }
}

// 格式化预览值
const formatPreviewValue = (value, valueType) => {
  switch (valueType) {
    case 'number':
      return Number(value)
    case 'boolean':
      return value === 'true' || value === true ? 'true' : 'false'
    case 'null':
      return 'null'
    default:
      return `"${value}"`
  }
}

// 获取值类型标签
const getValueTypeLabel = (valueType) => {
  const labelMap = {
    'string': 'String',
    'number': 'Number',
    'boolean': 'Boolean',
    'null': 'Null'
  }
  return labelMap[valueType] || valueType
}

// 切换字段替换说明显示/隐藏
const toggleReplaceHelp = () => {
  showReplaceHelp.value = !showReplaceHelp.value
}

// 启动转发任务
const startForwarding = async () => {
  try {
    // 表单验证
    if (!configFormRef.value) return
    const valid = await configFormRef.value.validate()
    if (!valid) return

    startLoading.value = true
    
    const response = await api.post('/kafka-forward/start', {
      kafka_config_id: forwardConfig.value.kafkaConfigId,
      source_topic: forwardConfig.value.sourceTopic,
      target_topic: forwardConfig.value.targetTopic,
      consume_strategy: forwardConfig.value.consumeStrategy,
      start_timestamp: forwardConfig.value.startTime,
      forward_strategy: forwardConfig.value.forwardStrategy,
      logic_operator: forwardConfig.value.logicOperator,
      match_conditions: forwardConfig.value.forwardStrategy === 'filter' ? 
        forwardConfig.value.matchConditions.filter(condition => 
          condition.type === 'key_value' ? (condition.key && condition.value) : condition.value
        ) : [],
      replace_rules: forwardConfig.value.forwardStrategy === 'replace' ?
        forwardConfig.value.replaceRules.filter(rule => rule.fieldPath && rule.newValue) : [],
      batch_size: forwardConfig.value.batchSize,
      process_interval: forwardConfig.value.processInterval,
      max_forward_count: forwardConfig.value.countLimitType === 'unlimited' ? 0 : forwardConfig.value.maxForwardCount
    })

    if (response.data.success) {
      ElMessage.success('转发任务启动成功')
      currentTaskStatus.value = response.data.data
      startStatsPolling()
      
      // 启动任务后重新开始轮询（如果已停止）
      if (!statusTimer.value) {
        noTaskPollCount.value = 0
        startStatusPolling()
      }
    } else {
      ElMessage.error('启动转发任务失败: ' + response.data.message)
    }
  } catch (error) {
    componentLogger.error('启动转发任务异常', error)
    ElMessage.error('启动转发任务异常: ' + error.message)
  } finally {
    startLoading.value = false
  }
}

// 停止当前任务
const stopCurrentTask = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要停止当前转发任务吗？',
      '确认停止',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    stopTaskLoading.value = true
    const response = await api.post('/kafka-forward/stop')

    if (response.data.success) {
      ElMessage.success('转发任务已停止')
      currentTaskStatus.value = null
      forwardStats.value = {}
      stopStatsPolling()
      // 停止任务后继续状态轮询，以便检测新任务
    } else {
      ElMessage.error('停止转发任务失败: ' + response.data.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('停止转发任务异常', error)
      ElMessage.error('停止转发任务异常: ' + error.message)
    }
  } finally {
    stopTaskLoading.value = false
  }
}

// 刷新任务状态
const refreshTaskStatus = async () => {
  await checkCurrentTaskStatus()
  
  // 如果轮询已停止，重新开始轮询
  if (!statusTimer.value) {
    componentLogger.info('手动刷新状态，重新开始轮询')
    noTaskPollCount.value = 0
    startStatusPolling()
  }
}

// 重置表单
const resetForm = () => {
  if (configFormRef.value) {
    configFormRef.value.resetFields()
  }
  forwardConfig.value = {
    kafkaConfigId: null,
    sourceTopic: '',
    targetTopic: '',
    consumeStrategy: 'latest',
    startTime: null,
    forwardStrategy: 'all',
    logicOperator: 'AND',
    matchConditions: [
      {
        type: 'key_value',
        key: '',
        value: ''
      }
    ],
    replaceRules: [
      {
        fieldPath: '',
        newValue: '',
        valueType: 'string'
      }
    ],
    batchSize: 100,
    processInterval: 1000,
    countLimitType: 'unlimited',
    maxForwardCount: 1000
  }
}

// 获取策略标签类型
const getStrategyTagType = (strategy) => {
  const typeMap = {
    'all': 'primary',
    'filter': 'warning',
    'replace': 'success',
    'transform': 'success'
  }
  return typeMap[strategy] || 'info'
}

// 获取策略文本
const getStrategyText = (strategy) => {
  const textMap = {
    'all': '全部转发',
    'filter': '条件过滤',
    'replace': '字段替换',
    'transform': '格式转换'
  }
  return textMap[strategy] || strategy
}

// 获取消费策略标签类型
const getConsumeStrategyTagType = (strategy) => {
  const typeMap = {
    'latest': 'success',
    'earliest': 'primary', 
    'timestamp': 'warning'
  }
  return typeMap[strategy] || 'info'
}

// 获取消费策略文本
const getConsumeStrategyText = (strategy) => {
  const textMap = {
    'latest': '最新',
    'earliest': '最早',
    'timestamp': '指定时间'
  }
  return textMap[strategy] || '未知'
}

// 格式化时间戳
const formatTimestamp = (timestamp) => {
  if (!timestamp) return '未设置'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.kafka-forward-container {
  padding: 0;
  min-height: calc(100vh - 60px);
  /* 统一使用纯灰色背景，与其他页面保持一致 */
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.title-with-back {
  display: flex;
  align-items: flex-start;
  gap: 15px;
}

.blue-return-button {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
  flex-shrink: 0;
  margin-top: 2px;
}

.blue-return-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.4);
  background: linear-gradient(135deg, #66b3ff 0%, #409eff 100%);
}

.title-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.title-main {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  font-size: 28px;
  color: #E6A23C;
  background: linear-gradient(135deg, #E6A23C 0%, #F0B86E 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.title-with-back h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  padding: 10px 16px;
  background: linear-gradient(135deg, #f5f7fa 0%, #ecf3fc 100%);
  border-left: 3px solid #E6A23C;
  border-radius: 6px;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.page-description .el-icon {
  font-size: 16px;
  color: #E6A23C;
  flex-shrink: 0;
}

.page-description span {
  flex: 1;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-icon {
  font-size: 20px;
  color: #E6A23C;
  background: linear-gradient(135deg, #E6A23C 0%, #F0B86E 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

/* 任务状态卡片 */
.current-task-status .task-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.info-item code {
  background: #f1f2f3;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

/* 配置表单 */
.config-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

/* 过滤条件样式 */
.filter-conditions {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 16px;
  background: #fafafa;
}

/* 统计面板 */
.stats-panel {
  border-radius: 12px;
}

.stats-panel .el-statistic {
  text-align: center;
}

/* Topic选择器样式 */
.topic-suggestion-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
}

.topic-suggestion-item .el-icon {
  color: #67c23a;
  font-size: 14px;
}

.topic-suggestion-item span {
  font-size: 14px;
  color: #303133;
}

/* 时间戳选择器样式 */
.timestamp-dialog {
  padding: 20px 0;
}

.timestamp-info {
  margin-bottom: 24px;
}

.timestamp-selector {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.datetime-inputs {
  display: flex;
  gap: 24px;
  align-items: center;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.input-group label {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.timestamp-preview {
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
}

.preview-info label {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 12px;
  display: block;
}

.preview-values {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preview-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.preview-item .label {
  font-size: 13px;
  color: #909399;
  min-width: 80px;
}

.preview-item code {
  background: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  color: #e6a23c;
}

.timestamp-icon {
  color: #409eff;
  cursor: pointer;
}

/* 快捷选择区域样式 */
.quick-select-section {
  margin-top: 24px;
  padding: 16px;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.quick-select-info {
  margin-bottom: 12px;
}

.quick-select-info label {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  display: block;
  margin-bottom: 4px;
}

.usage-tip {
  font-size: 12px;
  color: #909399;
  margin: 0;
  line-height: 1.4;
}

.quick-select-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.quick-select-buttons .el-button {
  margin: 0;
  border-radius: 16px;
  padding: 6px 12px;
  font-size: 12px;
  transition: all 0.2s ease;
}

.quick-select-buttons .el-button:hover {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
  transform: translateY(-1px);
}

/* 匹配条件配置样式 */
.filter-config-item {
  align-items: flex-start !important;
}

.filter-config-item .el-form-item__content {
  flex: 1;
}

.match-config-container {
  width: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: #fafafa;
}

.logic-selector {
  margin-bottom: 20px;
  padding: 16px;
  background: #f0f9ff;
  border-radius: 8px;
  border: 1px solid #b3d8ff;
}

.control-label {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-right: 12px;
}

.logic-operator {
  margin-top: 12px;
}

.conditions-list {
  margin-top: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: flex-start;
}

.condition-item {
  flex: 0 1 calc(50% - 8px); /* 默认每行显示2个 */
  min-width: 380px; /* 最小宽度，确保内容不会挤压 */
  max-width: calc(50% - 8px); /* 最大宽度限制 */
  box-sizing: border-box;
}

/* 大屏幕可以显示3个 */
@media (min-width: 1600px) {
  .condition-item {
    flex: 0 1 calc(33.333% - 11px); /* 每行显示3个 */
    max-width: calc(33.333% - 11px);
  }
}

/* 中等屏幕显示2个 */
@media (max-width: 1400px) and (min-width: 900px) {
  .condition-item {
    flex: 0 1 calc(50% - 8px);
    max-width: calc(50% - 8px);
  }
}

/* 小屏幕自动变为单列 */
@media (max-width: 900px) {
  .condition-item {
    flex: 0 1 100%;
    max-width: 100%;
  }
}

.condition-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  height: 100%; /* 确保同行卡片高度一致 */
  display: flex;
  flex-direction: column;
}

.condition-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.condition-number {
  font-size: 14px;
  font-weight: 600;
  color: #409eff;
}

.condition-content {
  display: flex;
  flex-direction: column;
  gap: 12px; /* 减小间距 */
  flex: 1; /* 占据剩余空间 */
}

.condition-row {
  display: flex;
  align-items: flex-start;
  gap: 12px; /* 减小间距 */
  flex-wrap: wrap;
}

.condition-label {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.condition-type {
  flex: 1;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
  min-width: 180px; /* 确保输入框有最小宽度 */
}

.input-label {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.add-condition-btn {
  flex: 0 1 100%; /* 占满整行 */
  margin-top: 0;
}

/* 替换规则样式 */
.replace-info {
  margin-bottom: 20px;
}

.replace-info-card {
  background: linear-gradient(135deg, #f5f7fa 0%, #f0f2f5 100%);
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.info-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 0;
  padding: 0 0 12px 0;
  border-bottom: 2px solid #e4e7ed;
  user-select: none;
  transition: all 0.3s ease;
}

.info-header:hover {
  background: rgba(64, 158, 255, 0.05);
  margin: 0 -20px;
  padding: 8px 20px 12px 20px;
  border-radius: 8px 8px 0 0;
}

.info-icon {
  font-size: 24px;
  color: #409eff;
}

.info-title {
  flex: 1;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.toggle-icon {
  font-size: 18px;
  color: #909399;
  transition: transform 0.3s ease;
}

.toggle-icon.is-expanded {
  transform: rotate(180deg);
}

.info-content {
  /* 折叠内容的容器 */
}

.info-section {
  margin-top: 20px;
  margin-bottom: 20px;
}

.info-section:first-child {
  margin-top: 20px;
}

.info-section:last-child {
  margin-bottom: 0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  margin-bottom: 12px;
}

.section-title .el-icon {
  font-size: 16px;
  color: #909399;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

@media (max-width: 1200px) {
  .info-grid {
    grid-template-columns: 1fr;
  }
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.info-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
  transform: translateY(-1px);
}

.item-icon {
  font-size: 20px;
  flex-shrink: 0;
  margin-top: 2px;
}

.item-content {
  flex: 1;
}

.item-label {
  font-size: 13px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.item-text {
  font-size: 12px;
  color: #606266;
  line-height: 1.6;
}

.item-text code {
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 11px;
  color: #e6a23c;
  border: 1px solid #e4e7ed;
}

.example-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.example-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 14px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  flex-wrap: wrap;
}

.field-path {
  background: #ecf5ff;
  padding: 4px 10px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 12px;
  color: #409eff;
  border: 1px solid #b3d8ff;
  font-weight: 500;
}

.field-value {
  padding: 4px 10px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 12px;
  font-weight: 500;
  border: 1px solid;
}

.string-value {
  background: #f0f9ff;
  color: #67c23a;
  border-color: #c2e7b0;
}

.number-value {
  background: #fef0e6;
  color: #e6a23c;
  border-color: #f5dab1;
}

.example-arrow {
  color: #909399;
  font-size: 16px;
  flex-shrink: 0;
}

.replace-preview {
  margin-top: 12px;
  padding: 10px;
  background: #f0f9ff;
  border-radius: 6px;
  border: 1px solid #b3d8ff;
}

.preview-label {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  font-size: 12px;
  font-weight: 500;
  color: #409eff;
}

.preview-content {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.preview-content code {
  background: #fff;
  padding: 3px 8px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  color: #606266;
  border: 1px solid #dcdfe6;
  word-break: break-all; /* 长文本自动换行 */
}

.preview-content code.new-value {
  color: #67c23a;
  font-weight: 600;
  border-color: #95d475;
}

.preview-arrow {
  color: #909399;
  font-size: 14px;
  flex-shrink: 0; /* 箭头不缩小 */
}

.field-hint {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
  font-style: italic;
}
</style>